#include "videorecver.h"
#include <QImage>
#include <QBuffer>
#include "messagepackage.h"

videoRecver::videoRecver(QString ip,int port,QObject *parent) : QObject(parent)
{
    this->ip=ip;
    this->port=port;
    socket = new QUdpSocket(this);
    socket->bind(QHostAddress::AnyIPv4,this->port,QAbstractSocket::ReuseAddressHint);
    socket->setSocketOption(QAbstractSocket::ReceiveBufferSizeSocketOption,300*2048);
    qDebug()<<socket->joinMulticastGroup(QHostAddress(this->ip));

}

videoRecver::~videoRecver()
{

}

void videoRecver::onReadyRead()
{
    QByteArray imageBytes;
    QBuffer buffer(&imageBytes);
    buffer.open(QIODevice::WriteOnly);
    int count = 0;
    int prevPackNum = 0;
    while(TaskSignal)
    {
        if(socket->hasPendingDatagrams())
        {
            ImagePackage pack = {};
            memset(&pack,0,sizeof(ImagePackage));
            socket->readDatagram((char*)&pack,sizeof(ImagePackage));
            qDebug()<<"当前包编号"<<pack.PackNum<<"上一个包编号"<<prevPackNum<<pack.packTaken;
            if(pack.PackNum < prevPackNum)
            {

                qDebug()<<count;
                QImage loadedImage;
                loadedImage.loadFromData(imageBytes,"JPG");



                emit recvComplete(loadedImage);

                prevPackNum = pack.PackNum;
                buffer.seek(0);
                imageBytes.clear();
                count = 0;
            }

            buffer.write(pack.data,pack.packTaken);
            count += pack.packTaken;
            prevPackNum = pack.PackNum;
        }
    }
}

void videoRecver::endTask()
{
    TaskSignal = false;
}
